//
//  GRSubmitOrderVC.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/8/24.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRSubmitOrderVC.h"
#import "GRStoreAction.h"
#import "GRPayWayView.h"
#import "GRPayPointConfirmView.h"
#import "GRBuyDiscountSuccessVC.h"
@interface GRSubmitOrderVC ()<GRPayWayViewDelegate,GRPayPointConfirmViewDelegate,GRPayManagerDelegate>
{
    NSInteger orderId;
}
@property (weak, nonatomic) IBOutlet UIImageView *goodImageView;

@property (weak, nonatomic) IBOutlet UILabel *nickNameLabel;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *discountLabel;

@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;

@property (weak, nonatomic) IBOutlet UITextField *countTF;

@property (weak, nonatomic) IBOutlet UILabel *pointLabel;
@property (weak, nonatomic) IBOutlet UILabel *reducePointLabel;
@property (weak, nonatomic) IBOutlet UISwitch *riceSwitch;

@property (weak, nonatomic) IBOutlet UILabel *payLabel;

@property (weak, nonatomic) IBOutlet UILabel *payDetailLabel;
@property(nonatomic,assign)CGFloat price;
@property(nonatomic,assign)CGFloat point;

@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property(nonatomic,strong)GRPayPointConfirmView * payPointConfirmView;
@property(nonatomic,assign)CGFloat getPoint;

@end

@implementation GRSubmitOrderVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = KGMTHEM_COLOR;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
}

-(GRPayPointConfirmView *)payPointConfirmView{
    if (!_payPointConfirmView) {
        _payPointConfirmView  = [GRPayPointConfirmView xx_instantiateFromNib];
        _payPointConfirmView.delegate = self;
        UIWindow * window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:_payPointConfirmView];
        [_payPointConfirmView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(window);
        }];
    }
    return _payPointConfirmView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self requestOrderData];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeText) name:UITextFieldTextDidEndEditingNotification object:self.countTF];
    [GRPayManager sharePay].delegate = self;
}
-(void)confirmPayAction{
    [self payOrdertWithPayType:1];
    
}

-(void)changeText{
    self.tipLabel.hidden = YES;
    if ([self.countTF.text integerValue] >30) {
        self.countTF.text = @"30";
        self.tipLabel.hidden = NO;
    }
    if ([self.countTF.text integerValue ]< 1) {
        self.countTF.text = @"1";
    }
    self.payLabel.text = [NSString stringWithFormat:@"%.2lf",self.price * [self.countTF.text integerValue ]];
    [self riceSwitchAction:self.riceSwitch];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.countTF resignFirstResponder];
}

-(void)requestOrderData{
    [GRStoreAction getdiscountAnalyOrderWithGoodId:_isOrder ?self.orderId: _goodId isOrder:_isOrder  ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        NSLog(@"%@",responseObject);
        if (success) {
            self.nickNameLabel.text = responseObject[@"nikeName"];
            self.titleLabel.text = responseObject[@"title"];
            [self.goodImageView sd_setImageWithURL:[NSURL URLWithString:responseObject[@"mainPhoto"]] placeholderImage:[UIImage imageNamed:@""]];
            self.payLabel.text = [NSString stringWithFormat:@"%.2lf",[responseObject[@"discountPrice"] floatValue] ] ;
            _price = [responseObject[@"discountPrice"] floatValue];
            self.pointLabel.text = [NSString stringWithFormat:@"龟米:%.2lf",[responseObject[@"point"] floatValue]];
            self.point = [responseObject[@"point"] floatValue];
            self.countTF.text = @"1";
            
            [self riceSwitchAction:self.riceSwitch];
        }
    }];
}

- (IBAction)riceSwitchAction:(UISwitch*)sender {
    if (sender.on) {
        if ([self.payLabel.text floatValue] > self.point) {
            self.reducePointLabel.text = [NSString stringWithFormat:@"-%.2lf",self.point];
        }else{
            self.reducePointLabel.text = [NSString stringWithFormat:@"-%@",self.payLabel.text];
        }
    }else{
        self.reducePointLabel.text = @"-0";
    }
    CGFloat dicountPoint = fabsf([self.reducePointLabel.text floatValue]);
    CGFloat payPrice = [self.payLabel.text floatValue] - dicountPoint;
    NSString * detailStr =  [NSString stringWithFormat:@"实付￥%.2lf 优惠￥%.2lf",payPrice ,dicountPoint];
    NSMutableAttributedString * attributeStr = [[NSMutableAttributedString alloc]initWithString:detailStr];
    NSRange rangeS =  [detailStr rangeOfString:@"实付" ];
    NSRange rangeF = [ detailStr rangeOfString:@"优惠" ];
    [attributeStr setAttributes:@{NSForegroundColorAttributeName:HEXCOLOR(0xF11544),NSFontAttributeName:[UIFont boldSystemFontOfSize:23]} range:NSMakeRange(rangeS.location+rangeS.length, rangeF.location - rangeS.length)];
    self.payDetailLabel.attributedText = attributeStr;
}

- (IBAction)addOrReduceCountAction:(UIButton *)sender {
    NSInteger count = [self.countTF.text integerValue];
    if (sender.tag - 1000 == 0) {
        if (count>1) {
               count--;
        }
    }else{
        if (count <30) {
             count++;
        }
    }
    self.tipLabel.hidden = count == 30?NO:YES;
    self.countTF.text = [NSString stringWithFormat:@"%ld",count];
    self.payLabel.text = [NSString stringWithFormat:@"%.2lf",self.price * count];
    [self riceSwitchAction:self.riceSwitch];
}


- (IBAction)submitAction:(id)sender {
    if (self.riceSwitch.on && fabsf([self.reducePointLabel.text floatValue]) == [self.payLabel.text floatValue]) {
        self.payPointConfirmView.hidden = NO;
        self.payPointConfirmView.payPricelabel.text = self.payLabel.text;
        self.payPointConfirmView.originalPriceLabel.text = self.payLabel.text;
        self.payPointConfirmView.pointLabel.text = [NSString stringWithFormat:@"-%.2lf",[self.payLabel.text floatValue]];
    }else{
        self.payPointConfirmView.hidden = YES;
        CGFloat payPrice = self.riceSwitch.on?[self.payLabel.text floatValue] - fabsf([self.reducePointLabel.text floatValue]):[self.payLabel.text floatValue];
        [GRPayWayView show:payPrice Delegate:self];
    }
}
-(void)payOrdertWithPayType:(NSInteger)payType{
    // 2支付宝支付 3.微信支付
      CGFloat payPrice = self.riceSwitch.on?[self.payLabel.text floatValue] - fabsf([self.reducePointLabel.text floatValue]):[self.payLabel.text floatValue];
    NSDictionary * dic = @{
                           @"costPoint":self.riceSwitch.on ? @(fabsf( [self.reducePointLabel.text floatValue])):@"0",
                           @"id":@(self.goodId),
                           @"num":self.countTF.text ,
                           @"orderId":@(self.orderId),
                           @"payType":payType == 1?@"point":payType == 2? @"alipay":@"wechat",
                           @"source":@"ios",
                           @"payMoney":[NSString stringWithFormat:@"%.2lf",payPrice],
                           @"totalMoney":self.payLabel.text
                           };
    [GRStoreAction createOrderWithDic:dic ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            NSLog(@"%@",responseObject);
            orderId = [responseObject[@"id"] integerValue];
            self.getPoint = [responseObject[@"addPoint"] floatValue];
            
            if (payType == 1) {
                self.payPointConfirmView.hidden = YES;
                [self paySuccess];
            }else{
                if (payType == 2) {
                    [[GRPayManager sharePay] aliPay: responseObject[@"payParam"][@"body"]];
                }else{
                    [GRPayManager WeChatPay:responseObject[@"payParam"]];
                }
            }
        }
    }];
    
    
}
/**
微信支付

@param payResp <#payResp description#>
*/
- (void)wechatPayResp:(BaseResp *)payResp{
    switch (payResp.errCode){
        case WXSuccess:{
            NSLog(@"支付成功");
            [self paySuccess];
        }
            break;
        case WXErrCodeUserCancel:{
            NSLog(@"已中断支付");
        }
            break;
        default:{
            NSLog(@"支付失败");
        }
            break;
    }
    NSLog(@"微信支付");
    
    
}

/**
 支付宝支付
 
 @param resultDic <#resultDic description#>
 */
- (void)alipayResultDic:(NSDictionary *)resultDic{
    if ([resultDic[@"resultStatus"] isEqual:@"9000"]) {
        NSLog(@"支付成功");
        [self paySuccess];
    }else if ([resultDic[@"resultStatus"] isEqual:@"6001"]){
        NSLog(@"已中断支付");
        
    }else{
        NSLog(@"支付失败");
    }
}

-(void)paySuccess {
     [[NSNotificationCenter defaultCenter] postNotificationName:@"paySuucess" object:nil];
    GRBuyDiscountSuccessVC * successVC = [[GRBuyDiscountSuccessVC alloc]init];
    successVC.orderId = orderId;
    successVC.type = BuyDiscountTypeSuccess;
    successVC.point = self.getPoint;
    [self.navigationController pushViewController:successVC animated:YES];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
